import React from 'react';
import { Card, Row, Col, Form, Icon, Table, Button, DatePicker, Select, Input, message, Modal , Switch, Pagination } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import '../style/index.less';
import store from 'store';

const { Option } = Select;
const { TextArea } = Input;
const SelectRequisition = Form.create()(
    class extends React.Component {
        constructor(){
            super();
            this.state = {
                visible: false,
                data: [],//主列表数据
                getBatchDetail: [],//详情列表数据
                total: 0,
                total2: 0,
                page: 1,
                page2: 1,
                pageSize: 10,
                pageSize2:10,
                locId: JSON.parse(window.sessionStorage.userData).locID,
                toLocID: '',
                rowKey: '',
                rowId: '',//双击行id
                defaultTime: {},
                ChineseEnglishSize: {}, //中英翻译
                User: JSON.parse(window.sessionStorage.userData),
            };
            this.columns = [
                {
                    key: 1,
                    title: this.state.User.language == 'EN'? 'Request number': '请求单号',
                    dataIndex: 'stkReqNO',
                    align: "center",
                    width: '200px'
                },
                {
                    key: 2,
                    title: this.state.User.language == 'EN'? 'Request department': '请求科室',
                    dataIndex: 'toLocDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 3,
                    title: this.state.User.language == 'EN'? 'Supply department': '供给科室',
                    dataIndex: 'frLocDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 5,
                    title: this.state.User.language == 'EN'? 'Request date': '请求日期',
                    dataIndex: 'createDate',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 6,
                    title: this.state.User.language == 'EN'? 'Document Type': '单据类型',
                    dataIndex: 'stateDesc',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 7,
                    title: this.state.User.language == 'EN'? 'Prepared by': '制单人',
                    dataIndex: 'createUserName',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 8,
                    title: this.state.User.language == 'EN'? 'Transfer status': '转移状态',
                    dataIndex: 'tranStatus',
                    align: "center",
                    width: '100px',
                },
            ];
            this.columnsDetail = [
                {
                    key: 2,
                    title: this.state.User.language == 'EN'? 'Drug code': '药品代码',
                    dataIndex: 'stockCode',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 3,
                    title: this.state.User.language == 'EN'? 'Drug Name': '药品名称',
                    dataIndex: 'stockDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 5,
                    title: this.state.User.language == 'EN'? 'Supplier inventory': '供应方库存',
                    dataIndex: 'frLocQtyUom',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 6,
                    title: this.state.User.language == 'EN'? 'Number of requests': '请求数量',
                    dataIndex: 'qty',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 7,
                    title: this.state.User.language == 'EN'? 'Transferred quantity': '已转移数量',
                    dataIndex: 'transQtyUom',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 8,
                    title: this.state.User.language == 'EN'? 'Untransferred quantity': '未转移数量',
                    dataIndex: 'leftQtyUom',
                    align: "center",
                    width: '150px',
                },
                {
                    key: 9,
                    title: this.state.User.language == 'EN'? 'unit': '单位',
                    dataIndex: 'unitDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 10,
                    title: this.state.User.language == 'EN'? 'Price': '售价',
                    dataIndex: 'sp',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 11,
                    title: this.state.User.language == 'EN'? 'Manufacturer': '生产厂家',
                    dataIndex: 'manfDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 12,
                    title: this.state.User.language == 'EN'? 'specification': '规格',
                    dataIndex: 'stockSpec',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 13,
                    title: this.state.User.language == 'EN'? 'common name': '通用名',
                    dataIndex: 'generDesc',
                    align: "center",
                    width: '200px',
                },
                {
                    key: 14,
                    title: this.state.User.language == 'EN'? 'Formulation': '剂型',
                    dataIndex: 'formDesc',
                    align: "center",
                    width: '100px',
                },
                {
                    key: 15,
                    title: this.state.User.language == 'EN'? 'Remarks': '备注',
                    dataIndex: 'remark',
                    align: "center",
                    width: '200px',
                },
            ];
            this.myRef14 = React.createRef();
        }

        componentDidMount() {
            this.props.onRef(this);
        }

        //props变化是即使更新props
        componentWillReceiveProps(props){
            this.setState({locId: props.inOpLocDr, toLocID: props.toLocDr,ChineseEnglishSize: props.ChineseEnglishSize})
        }

        // 获取列表数据
        getTableData=(startDate, endDate, state) => {
            this.props.form.validateFields((errors, values) => {
                let obj = JSON.parse(JSON.stringify(values));
                if(errors == null){
                    let {page, pageSize} = this.state;
                    let data = {
                        params: [
                            {
                                begin: obj.StartDate ? Moment(obj.StartDate).format('YYYY-MM-DD') : this.state.defaultTime.params ? Moment(this.state.defaultTime.params.startDate).format('YYYY-MM-DD') : '',
                                end: obj.EndDate ? Moment(obj.EndDate).format('YYYY-MM-DD') : this.state.defaultTime.params ? Moment(this.state.defaultTime.params.endDate).format('YYYY-MM-DD') : '',
                                stateID: '20',
                                toLocID: obj.ReLoc ? obj.ReLoc : undefined,
                                frLocID: obj.geLoc ? obj.geLoc : undefined,
                                transStatus: obj.approve2 ? 1 : obj.approve ? 2 : 0
                            }
                        ],
                        pagination: [
                            {
                                pageSize: pageSize,
                                currentPage: page,
                                sort: "",
                                dir: "",
                            }
                        ],
                    };
                    $http.post('urlS', this, {
                        code: "02020231",
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                if(res.rows.length > 0){
                                    for(var i = 0; i < res.rows.length; i++) {
                                        res.rows[i].key = i;
                                    }
                                    this.setState({data: res.rows, total: res.total});
                                }else {
                                    this.setState({data: [], total: 0});
                                    message.error('没数据');
                                }
                            }
                        }
                    })
                }
            });

        }


        // 打开弹框
        showModal = (time) => {
            this.setState({
                visible: true,
                defaultTime: time
            }, () => {
                this.getTableData();
            });
        };
        // 关闭
        handleCancel = (e) => {
            this.setState({
                visible: false,
                getBatchDetail: [],
                total2: 0,
                rowKey: '',
                rowId: '',
                data: [],//主列表数据
                total: 0,
                page: 1,
                page2: 1,
                pageSize: 10,
                pageSize2:10,
                locId: '',
                toLocID: '',
            });
        };

        // 重置表单
        resetFields = () => {
            this.props.form.resetFields(); //清空所有
            this.setState({
                getBatchDetail: [],
                total2: 0,
                rowKey: '',
                rowId: '',
                data: [],//主列表数据
                total: 0,
            });
        };

        // 显示分页总条数
        showTotal(total) {
            return `共 ${total} 条`;
        }

        // 页码改变的回调，参数是改变后的页码及每页条
        onChange = (page, pageSize) => {
            this.setState({page: page, pageSize: pageSize}, () => {
                let {startDate, endDate, status} = this.state;
                this.getTableData()
            })
        };

        // 条数改变的回调
        onShowSizeChange = (current, size) => {
            this.setState({page: 1, pageSize: size}, () => {
                let {startDate, endDate, status} = this.state;
                this.onChange(current, size)
            })
        };
        // 页码改变的回调，参数是改变后的页码及每页条
        onChange2 = (page, pageSize) => {
            this.setState({page: page, pageSize2: pageSize}, () => {
                let {startDate, endDate, status} = this.state;
                this.BatchDetail(this.state.rowId);
            })
        };

        // 条数改变的回调
        onShowSizeChange2 = (current, size) => {
            this.setState({page: 1, pageSize2: size}, () => {
                let {startDate, endDate, status} = this.state;
                this.onChange2(current, size)
            })
        };
        BatchDetail=(id )=>{

            let data = {
                params: [
                    {
                        stkReqID: id
                    }
                ],
                pagination: [
                    {
                        pageSize: this.state.pageSize2,
                        currentPage: this.state.page2,
                        sort: "",
                        dir: "",
                    }
                ],
            };
            $http.post('urlS', this, {
                code: "02020141",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        for(var i = 0; i < res.rows.length; i++) {
                            res.rows[i].key = i;
                        }
                        this.setState({getBatchDetail: res.rows, total2: res.total});
                    }else {
                        this.setState({getBatchDetail: [], total2: 0});
                    }
                }
            })

        };

        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({rowKey: record.key, rowId: record.stkReqID});
                        this.BatchDetail(record.stkReqID);
                    } else {
                        if (this.state.rowKey !== record.key) {
                            this.setState({rowKey: record.key,rowId: record.stkReqID});
                            this.BatchDetail(record.stkReqID);
                        } else {
                            this.setState({rowKey: '', rowId: '', getBatchDetail: [], total2: 0});
                        }
                    }
                },
                onDoubleClick: () => {
                    // 保存行数据以及ID
                    this.setState({rowId: record.stkReqID}, () => {
                        this.handleOk();
                    })
                }
            }
        };

        // 确定
        handleOk = (e) => {
            if (this.state.rowId) {
                this.props.handleThis.onDoubleClickRequisition(this.state.rowId);
                this.handleCancel()
            } else {
                message.error("请选择一条需要操作的数据");
            }
        };

        // 表格行的类名
        setRowClassName = (record) => {
            return record.key === this.state.rowKey ? 'clickRowStyle' : '';
        };

        onSwitchState=()=>{
            if(this.props.form.getFieldValue('approve2')){
                this.props.form.setFieldsValue({approve2: false})
            }
        };
        onSwitchAllState=()=>{
            if(this.props.form.getFieldValue('approve')){
                this.props.form.setFieldsValue({approve: false})
            }
        };

        render() {

            const formItemInput  = {
                labelCol: { span: 6 },
                wrapperCol: { span: 18 },
            };
            const formItemLayout = {    // label 和input宽度
                labelCol: { span:10 },
                wrapperCol: { span: 14 },
            };
            const { getFieldDecorator } = this.props.form;
            let {ChineseEnglishSize, User} = this.state;
            return (
                <Modal
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText={ChineseEnglishSize.StockTransferMakingFormdetermine ? ChineseEnglishSize.StockTransferMakingFormdetermine.descripts:'确定'}
                    cancelText={ChineseEnglishSize.StockTransferMakingFormcancel ? ChineseEnglishSize.StockTransferMakingFormcancel.descripts:'取消'}
                    width='75%'
                    height='85%'
                    className="selectRequisition"
                >
                    <div>
                        <Row>
                            <Card
                                size='small'
                                title={ChineseEnglishSize.StockTransferMakingFormselectRequestForm ? ChineseEnglishSize.StockTransferMakingFormselectRequestForm.descripts:'选取请求单'}
                                className="condition"
                            >
                                <Form >
                                    <Row>
                                        <Col span={18} className="top-form">
                                                <Row>
                                                    <Col span={8}>
                                                        <Form.Item label={ChineseEnglishSize.StockTransferMakingFormtoLoc ? ChineseEnglishSize.StockTransferMakingFormtoLoc.descripts:'请求科室'} {...formItemInput}>
                                                            {getFieldDecorator('ReLoc', {
                                                                initialValue: undefined,
                                                                rules: [{ required: false, message: '请求科室不能为空' }]
                                                            })(
                                                                <Select showSearch allowClear placeholder={ChineseEnglishSize.StockTransferMakingFormtoLocTips ? ChineseEnglishSize.StockTransferMakingFormtoLocTips.descripts:'请选择请求科室'} >
                                                                    {this.props.SelectData.loc && this.props.SelectData.loc.map((item, i) => {
                                                                        return <Option key={i} value={item.id}>{item.descripts}</Option>
                                                                    })}
                                                                </Select>
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item label={ChineseEnglishSize.StockTransferMakingFormstartDate ? ChineseEnglishSize.StockTransferMakingFormstartDate.descripts:'起始日期'} {...formItemInput}>
                                                            {getFieldDecorator('StartDate', {
                                                                initialValue: this.props.SelectData.params ? Moment(this.props.SelectData.params.startDate) : undefined,
                                                            })(
                                                                <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" />
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item {...formItemLayout} label={ChineseEnglishSize.StockTransferMakingFormshowThetransferIsCompleteMedic ? ChineseEnglishSize.StockTransferMakingFormshowThetransferIsCompleteMedic.descripts:'显示转移完成药品'}>
                                                            {getFieldDecorator('approve',{
                                                                valuePropName: 'checked',
                                                                initialValue: false,
                                                                rules:[{required: false}]
                                                            })(
                                                                User.language == 'EN' ? <Switch checkedChildren="Yes" unCheckedChildren="No" onClick={this.onSwitchState} /> : <Switch checkedChildren="是" unCheckedChildren="否" onClick={this.onSwitchState} />

                                                            ) }
                                                        </Form.Item>
                                                    </Col>
                                                </Row>
                                                <Row>
                                                    <Col span={8}>
                                                        <Form.Item label={ChineseEnglishSize.StockTransferMakingFormfrLoc ? ChineseEnglishSize.StockTransferMakingFormfrLoc.descripts:'供给科室'} {...formItemInput}>
                                                            {getFieldDecorator('geLoc', {
                                                                initialValue: undefined,
                                                                rules: [{ required: false, message: '供给科室不能为空' }]
                                                            })(
                                                                <Select showSearch allowClear placeholder={ChineseEnglishSize.StockTransferMakingFormfrLocTips ? ChineseEnglishSize.StockTransferMakingFormfrLocTips.descripts:'请选择供给科室'} >
                                                                    {this.props.SelectData.loc && this.props.SelectData.loc.map((item, i) => {
                                                                        return <Option key={i} value={item.id}>{item.descripts}</Option>
                                                                    })}
                                                                </Select>
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item label={ChineseEnglishSize.StockTransferMakingFormendDate ? ChineseEnglishSize.StockTransferMakingFormendDate.descripts:'截至日期'} {...formItemInput}>
                                                            {getFieldDecorator('EndDate', {
                                                                initialValue:  this.props.SelectData.params ? Moment(this.props.SelectData.params.endDate) : undefined,
                                                            })(
                                                                <DatePicker style={{width: '100%'}} format="YYYY-MM-DD" />
                                                            )}
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={8}>
                                                        <Form.Item {...formItemLayout} label={ChineseEnglishSize.StockTransferMakingFormincludePartialTransfer ? ChineseEnglishSize.StockTransferMakingFormincludePartialTransfer.descripts:'包含部分转移'}>
                                                            {getFieldDecorator('approve2',{
                                                                valuePropName: 'checked',
                                                                initialValue: false,
                                                                rules:[{required: false}]
                                                            })(
                                                                User.language == 'EN' ? <Switch checkedChildren="Yes" unCheckedChildren="No" onClick={this.onSwitchAllState} /> : <Switch checkedChildren="是" unCheckedChildren="否" onClick={this.onSwitchAllState} />
                                                            ) }
                                                        </Form.Item>
                                                    </Col>
                                                </Row>
                                        </Col>
                                        <Col span={5} style={{marginLeft: '33px'}}>
                                            <Row style={{marginBottom: '20px',marginTop: '5px'}}>
                                                <Button  type="primary" style={{marginRight: '30px'}} onClick={()=> {this.props.handleThis.show();this.getTableData()}} ref={this.myRef14}>{ChineseEnglishSize.StockTransferMakingFormsearch ? ChineseEnglishSize.StockTransferMakingFormsearch.descripts:'查询'}</Button>
                                                <Button style={{marginRight: '30px'}} onClick={this.resetFields}>{ChineseEnglishSize.StockTransferMakingFormclean ? ChineseEnglishSize.StockTransferMakingFormclean.descripts:'清屏'}</Button>
                                            </Row>
                                        </Col>
                                    </Row>
                                </Form>
                            </Card>
                        </Row>
                        <Row>
                            <Col  span={10}>
                                <Card
                                    size='small'
                                    title={ChineseEnglishSize.StockTransferMakingFormrequestForm ? ChineseEnglishSize.StockTransferMakingFormrequestForm.descripts:'请求单'}
                                >
                                    <div style={{height: store.getState().tableHeight.y - 86 + 'px'}}>
                                        <Table
                                            columns={this.columns}
                                            dataSource={this.state.data}
                                            pagination={false}
                                            bordered
                                            scroll={{ x: 1000, y: store.getState().tableHeight.y - 120 }}
                                            onRow={this.onClickRow}
                                            rowClassName={this.setRowClassName}
                                        />
                                        <Pagination
                                            showTotal={() => this.showTotal(this.state.total)}
                                            size="small"
                                            showQuickJumper
                                            showSizeChanger
                                            defaultCurrent={1}
                                            current={this.state.page}
                                            total={this.state.total}
                                            onChange={this.onChange}
                                            onShowSizeChange={this.onShowSizeChange}
                                            style={{textAlign: "right", marginTop: '13px'}}
                                        />
                                    </div>
                                </Card>
                            </Col>
                            <Col  span={14}>
                                <Card
                                    size='small'
                                    title={ChineseEnglishSize.StockTransferMakingFormrequestFormDetails ? ChineseEnglishSize.StockTransferMakingFormrequestFormDetails.descripts:'请求单明细'}
                                >
                                    <div style={{height: store.getState().tableHeight.y - 86 + 'px'}}>
                                        <Table
                                            columns={this.columnsDetail}
                                            dataSource={this.state.getBatchDetail}
                                            pagination={false}
                                            bordered
                                            scroll={{ x: 2050, y: store.getState().tableHeight.y - 120 }}
                                        />
                                        <Pagination
                                            showTotal={() => this.showTotal(this.state.total2)}
                                            size="small"
                                            showQuickJumper
                                            showSizeChanger
                                            defaultCurrent={1}
                                            current={this.state.page2}
                                            total={this.state.total2}
                                            style={{textAlign: "right", marginTop: '13px'}}
                                            onChange={this.onChange2}
                                            onShowSizeChange={this.onShowSizeChange2}
                                        />
                                    </div>
                                </Card>
                            </Col>
                        </Row>
                    </div>

                </Modal>

            )
        }


    }
);
export default SelectRequisition